<template>
  <div class="user-manage w-full h-full display-flex">
    <div class="left-search h-full">
      <!-- v-model="selectedOrg" -->
      <a-tree
        v-if="orgTreeData.length > 0"
        bordered
        :show-line="true"
        :defaultExpandAll="true"
        :tree-data="orgTreeData"
        @select="onSelect"
      >
      </a-tree>
    </div>
    <div class="right-table h-full">
      <div class="top-btns w-full">
        <a-space>
          <a-button type="primary" @click="onAdd">新增</a-button>
          <a-button type="primary" @click="onModify" :disabled="isSelectedOne">修改</a-button>
          <a-button type="danger" @click="onDelete" :disabled="isSelectedOne">删除</a-button>
          <a-button type="primary" @click.stop.prevent="onLock()" :disabled="isSelected">锁定</a-button>
          <a-button type="primary" @click.stop.prevent="resetPassword()" :disabled="isSelected">重置密码</a-button>
          <a-input-search
            v-model="filter.filterText"
            placeholder="请输入查询条件"
            @search="loadData"
            style="width: 300px;"
            enter-button
          />
        </a-space>
      </div>
      <a-table
        style="height:calc(100% - 40px);overflow-y:auto;"
        bordered
        :columns="table.columns"
        :row-selection="table.rowSelection"
        :rowKey="record => record.id"
        :data-source="table.dataSource"
        :pagination="table.pagination"
      >
        <template slot="state" slot-scope="text">
          {{ judgeState(text) }}
        </template>
        <span slot="appKey" slot-scope="text">{{ text }}</span>
        <span slot="appSecret" slot-scope="text, row">
          <a @click.stop.prevent="showAppSecret(row)" class="a-edit" title="点击获取应用密钥">********</a>
        </span>
      </a-table>
    </div>
  </div>
</template>

<script>
import orgService from '@/api/uom/orgService'
import userService from '@/api/uom/userService'
import notification from 'ant-design-vue/es/notification'
import moment from 'moment'

import orupService from '@/api/orupService'
import systemManageService from '@/api/systemManageService'

const columns = [
  {
    title: '用户名',
    align: 'center',
    dataIndex: 'name'
  },
  {
    title: '账户',
    align: 'center',
    dataIndex: 'account'
  },
  {
    title: '密码',
    align: 'center',
    dataIndex: 'password'
  },
  {
    title: '状态',
    align: 'center',
    dataIndex: 'status'
  },
  {
    title: '注册时间',
    align: 'center',
    dataIndex: 'createTime',
    customRender: (text) => {
      return moment(text).format('YYYY-MM-DD HH:mm:ss')
    }
  },
  {
    title: '更新时间',
    align: 'center',
    dataIndex: 'modifyTime',
    customRender: (text) => {
      return moment(text).format('YYYY-MM-DD HH:mm:ss')
    }
  }
]

export default {
  name: 'UserManage',
  data () {
    return {
      orgTreeData: [],
      userData: [],
      selectedOrg: '',

      search: '',
      treeData: [],
      stateList: [],
      expandedKeys: [],
      filter: {
        filterText: '',
        pageIndex: 1,
        pageSize: 10
      },
      table: {
        columns: columns,
        dataSource: [],
        rowSelection: {
          selectedRowKeys: [],
          selectedRow: {},
          onChange: (selectedRowKeys, selectedRows) => {
            this.table.rowSelection.selectedRowKeys = selectedRowKeys.length ? [selectedRowKeys.pop()] : []
            this.table.rowSelection.selectedRow = selectedRows.length ? selectedRows.pop() : {}
          }
        },
        pagination: {
          pageSize: 10,
          total: 0,
          current: 1,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100', '200', '500'],
          showTotal: (total) => `共${total}条数据`,
          onShowSizeChange: (current, pageSize) => {
            this.filter.pageIndex = 1
            this.filter.pageSize = pageSize
          },
          onChange: (current, pageSize) => {
            this.filter.pageIndex = current
            this.filter.pageSize = pageSize
            this.table.pagination.current = current
          }
        }
      }
    }
  },

  mounted () {
    this.getOrgData()
    // this.loadData()
  },

  methods: {
    async getOrgData () {
      this.orgTreeData = await orgService.getOrgTree({})
    },
    async getUserData () {
      this.userData = await userService.getUserList(this.selectedOrg[0])
      this.table.dataSource = this.userData
    },
    onSelect (list) {
      if (list && list.length > 0) {
        this.selectedOrg = list
        this.getUserData()
      } else {
        notification.error({ message: '无数据' })
      }
    },
    onAdd () {
      if (this.selectedOrg.length < 1) {
        this.$message.warning('请先选择左侧组织机构!')
      } else {
        this.openDialog()
      }
    },
    onModify () {
      this.openDialog(this.table.rowSelection.selectedRow)
    },
    onDelete () {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认删除该数据吗？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          const row = _this.table.rowSelection.selectedRow
          orupService.userManageDelete(row).then(res => {
            if (res) {
              _this.loadData()
              _this.$message.success('删除成功!')
            }
          })
        }
      })
    },
    onLock (record) {
      this.$confirm({
        content: '确认锁定该账号？',
        okType: 'danger',
        onOk: () => {
          systemManageService.lockUser({ appId: record.id }).then(res => {
            this.$message.success('应用账号已锁定')
            this.loadData()
          })
        }
      })
    },
    resetPassword (record) {
      this.$confirm({
        content: '确认重置该账号密钥？',
        okType: 'danger',
        onOk: () => {
          systemManageService.resetUserAppSecret({ appId: record.id }).then(res => {
            this.$message.success('应用密钥信息已更新，请及时替换!')
            this.loadData()
          })
        }
      })
    },
    openDialog (record) {
      const _this = this
      this.$dialog({
        title: '新建用户',
        content: () => import('@/views/system/user/UserDialog'),
        width: 500,
        bodyStyle: { height: '290px' },
        props: {
          record: record
        },
        centered: true,
        maskClosable: false,
        on: {
          ok (ctl) {
            const dialogCtl = ctl.getDialogCtl()
            if (dialogCtl.onSubmit()) {
              if (record && record.id) {
                orupService.userManageUpdate(dialogCtl.form).then(res => {
                  if (res && res.id) {
                    _this.$message.success('修改成功!')
                    _this.loadData()
                    _this.table.rowSelection.selectedRowKeys = []
                    _this.table.rowSelection.selectedRow = {}
                  }
                })
              } else {
                orupService.userManageSave(_this.selectedOrg.pop(), dialogCtl.form).then(res => {
                  if (res && res.id) {
                    _this.$message.success('添加成功!')
                    _this.loadData()
                    _this.selectedOrg = []
                  }
                })
              }
              ctl.closeDialog()
            }
          }
        }
      })
    },
    moment,
    loadData () {
      const params = {
        pageIndex: this.filter.pageIndex - 1,
        pageSize: this.filter.pageSize,
        filterText: this.filter.filterText,
        userState: 0
      }
      orupService.userManageListQuery(params).then(res => {
        if (res && res.length > 0) {
          this.table.dataSource = res
        } else {
          this.$message.warning('没有相关用户!')
          this.filter.filterText = ''
        }
      })
    },
    judgeState (text) {
      const data = this.stateList.filter(item => {
        return item.state === text
      })
      if (data && data.length > 0) {
        return data[0].description
      } else {
        return ''
      }
    },
    showAppSecret (record) {
      systemManageService.userInfoCopy({ appId: record.id }).then(res => {
        this.$dialog({
          title: '应用[' + record.appName + ']密钥',
          content: () => import('@v/investmentOnline/systemManage/dialog/UserSecretDialog.vue'),
          width: 550,
          props: {
            record: res
          },
          centered: true,
          maskClosable: false,
          on: {
            ok (ctl) {
              ctl.closeDialog()
            }
          }
        })
      })
    }
  },
  computed: {
    isSelectedOne () {
      return !this.table.rowSelection.selectedRowKeys ||
        this.table.rowSelection.selectedRowKeys.length !== 1
    },
    isSelected () {
      return !this.table.rowSelection.selectedRowKeys ||
        this.table.rowSelection.selectedRowKeys.length < 1
    }
  }
}
</script>

<style lang="less" scoped>
.user-manage {
  padding: 10px;
  background: #fff;

  .left-search {
    width: 20%;
  }

  .right-table {
    width: 80%;
    padding-left: 10px;

    .top-btns {
      height: 40px;
    }
  }
}
</style>
